package cn.com.api.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.com.api.entity.ApiU_dynamic;
import cn.com.api.entity.ApiU_dynamic_remind;
import cn.com.api.entity.ApiU_dynamic_reply;
import cn.com.api.entity.ApiU_dynamic_rule;
import cn.com.api.entity.ApiU_dynamic_source;

import cn.com.api.service.ApiU_dynamicService;
import cn.com.api.service.ApiU_dynamic_remindService;
import cn.com.api.service.ApiU_dynamic_replyService;
import cn.com.api.service.ApiU_dynamic_ruleService;
import cn.com.api.service.ApiU_dynamic_sourceService;
import cn.com.api.service.CheckService;

import cn.com.util.*;

@Controller
@RequestMapping(Utils.SYS_API + "dynamic/")
public class ApiU_dynamicController {
	@Autowired
	private ApiU_dynamicService apiU_dynamicService;
	@Autowired
	private ApiU_dynamic_sourceService apiU_dynamic_sourceService;
	@Autowired
	private ApiU_dynamic_replyService apiU_dynamic_replyService;
	@Autowired
	private ApiU_dynamic_remindService apiU_dynamic_remindService;
	@Autowired
	private ApiU_dynamic_ruleService apiU_dynamic_ruleService;
	@Autowired
	private CheckService checkService;

	private static Logger logger = Logger.getLogger(ApiU_dynamicController.class);

	/**
	 * 发布动态
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "dynamic_publish")
	public void dynamic_publish(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String user_id = request.getParameter("user_id");
		String token = request.getParameter("token");

		String context = request.getParameter("context");
		// String type = request.getParameter("type");
		String content_type = request.getParameter("content_type");
		String is_open = request.getParameter("is_open");
		String longitude = request.getParameter("longitude");
		String latitude = request.getParameter("latitude");
		String address = request.getParameter("address");
		String atWho = request.getParameter("atWho"); // 提醒谁看，User_id,用,分隔
		String resources = request.getParameter("resources");// 图片或视频，多张图片以，分隔

		Map<String, Object> map = new HashMap<String, Object>();

		try {
			if (checkService.checkToken(user_id, token, map)) {
				ApiU_dynamic dynamic = new ApiU_dynamic();
				dynamic.setUser_id(user_id);
				dynamic.setAdd_time(Util.CurrentTime());
				dynamic.setContext(context);
				dynamic.setIs_delete(0);
				dynamic.setType(0); // 动态
				dynamic.setIs_against(0);
				dynamic.setContent_type(Integer.valueOf(content_type));
				dynamic.setStatus(1);
				dynamic.setIs_open(Integer.valueOf(is_open));
				dynamic.setLongitude(longitude);
				dynamic.setLatitude(latitude);
				if (Util.isNull(address)) {
					dynamic.setAddress("");// 不公开地址
				} else {
					dynamic.setAddress(address);
				}

				apiU_dynamicService.U_dynamicInsertion(dynamic);

				// 图片或视频
				if (!Util.isNull(resources) && !resources.equals("")) {
					String[] res = resources.split(",");
					Integer iSort = 0;
					for (String re : res) {
						ApiU_dynamic_source dynamic_source = new ApiU_dynamic_source();
						dynamic_source.setDynamic_id(dynamic.getId().toString());
						dynamic_source.setSource(re.toString());
						dynamic_source.setSort(iSort);
						dynamic_source.setType(Integer.valueOf(content_type));
						apiU_dynamic_sourceService.U_dynamic_sourceInsertion(dynamic_source);
					}
				}

				// 提醒谁看
				if (!Util.isNull(atWho) && !atWho.equals("")) {
					String[] uidS = atWho.split(",");
					for (String uid : uidS) {
						ApiU_dynamic_remind dynamic_remind = new ApiU_dynamic_remind();
						dynamic_remind.setDynamic_id(dynamic.getId().toString());
						dynamic_remind.setUser_id(uid.toString());
						dynamic_remind.setUpdate_time(Util.CurrentTime());
						dynamic_remind.setIs_read(0);
						apiU_dynamic_remindService.U_dynamic_remindInsertion(dynamic_remind);
					}
				}
				// return
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "添加成功！");
			}

		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 我的动态列表--不包含回复内容
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("myDynamicInfo")
	public void myDynamicInfo(HttpServletRequest request, HttpServletResponse response, String user_id, String token,
			PageInfo page) throws Exception {

		// String user_id = request.getParameter("user_id");
		// String token = request.getParameter("token");

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if (checkService.checkToken(user_id, token, map)) {
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("user_id", user_id);
				param.put("type", "0");
				List<ApiU_dynamic> dynamicList = apiU_dynamicService.findDynamicInfoByUser_id(param, page);
				// return
				map.put(Utils.DATAS, dynamicList);
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "查询成功！");
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		JsonUtil.printJson(response, JsonUtil.object2json(map));

	}

	/**
	 * 查看别人动态列表--不包含回复内容
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("userDynamicInfo")
	public void userDynamicInfo(HttpServletRequest request, HttpServletResponse response, String user_id, String token,
			String touser_id, PageInfo page) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if (checkService.checkToken(user_id, token, map)) {
				map.clear();
				map = apiU_dynamicService.findDynamicInfoByUser_id(user_id, touser_id, page);
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		JsonUtil.printJson(response, JsonUtil.object2json(map));

	}

	/**
	 * 动态列表(朋友圈)--包含回复内容
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("DynamicInfo")
	public void DynamicInfo(HttpServletRequest request, HttpServletResponse response, String user_id, String token,
			PageInfo page) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if (checkService.checkToken(user_id, token, map)) {
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("user_id", user_id);
				param.put("type", 0);
				List<ApiU_dynamic> dynamicList = apiU_dynamicService.findDynamicInfo(user_id, page);
				// return
				map.put(Utils.DATAS, dynamicList);
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "查询成功！");
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		JsonUtil.printJson(response, JsonUtil.object2json(map));

	}

	/**
	 * 删除动态（仅自己可以删除自己的）
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("DelDynamicsByID")
	public void DelDynamicsByID(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String user_id = request.getParameter("user_id");
		String token = request.getParameter("token");

		String id = request.getParameter("id");

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if (checkService.checkToken(user_id, token, map)) {
				ApiU_dynamic dynamic = apiU_dynamicService.findU_dynamicById(Integer.valueOf(id));
				dynamic.setIs_delete(1);
				apiU_dynamicService.updateU_dynamic(dynamic);
				// return
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "删除成功！");
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		JsonUtil.printJson(response, JsonUtil.object2json(map));

	}

	/**
	 * 回复动态（回复动态和at回复）
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("replyDynamicByID")
	public void replyDynamicByID(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String user_id = request.getParameter("user_id");// 回帖人ID
		String token = request.getParameter("token");
		String dynamic_id = request.getParameter("dynamic_id");// 动态ID
		String reply_content = request.getParameter("reply_content");
		String user_name = request.getParameter("user_name");// 回帖人姓名
		String to_id = request.getParameter("to_uid");// 被at人的ID, 为-1时，表示回复的主帖
		String to_uname = request.getParameter("to_uname");// 被at人的姓名

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if (checkService.checkToken(user_id, token, map)) {
				// 保存回复内容
				ApiU_dynamic_reply dynamic_reply = new ApiU_dynamic_reply();
				dynamic_reply.setDynamic_id(dynamic_id);
				dynamic_reply.setUser_id(user_id);
				dynamic_reply.setUser_name(user_name);
				dynamic_reply.setReply_content(reply_content);
				dynamic_reply.setTo_uid(to_id);
				dynamic_reply.setTo_uname(to_uname);
				dynamic_reply.setAdd_time(Util.CurrentTime());
				dynamic_reply.setIs_delete(0);
				Integer ret = apiU_dynamic_replyService.U_dynamic_replyInsertion(dynamic_reply);
				if (ret > 0) {
					// 保存回复提醒
					if (!Util.isNull(to_id) && !to_id.equals("-1")) {
						ApiU_dynamic_remind dynamic_remind = new ApiU_dynamic_remind();
						dynamic_remind.setDynamic_id(dynamic_id);
						dynamic_remind.setUser_id(to_id);
						dynamic_remind.setUpdate_time(Util.CurrentTime());
						dynamic_remind.setIs_read(0);
						apiU_dynamic_remindService.U_dynamic_remindInsertion(dynamic_remind);
					}
					// return
					map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
					map.put(Utils.MESSAGE, "回复成功！");
					map.put(Utils.DATAS, dynamic_reply);
				} else {
					map.put(Utils.RESULT, Utils.RESULT_RC_PARAMTER_ERROR);
					map.put(Utils.MESSAGE, "回复失败！");
				}
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		JsonUtil.printJson(response, JsonUtil.object2json(map));

	}

	/**
	 * 删除回复内容（仅自己可以删除自己的）
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("DelDynamics_ReplyByID")
	public void DelDynamics_ReplyByID(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String user_id = request.getParameter("user_id");
		String token = request.getParameter("token");
		String id = request.getParameter("id");
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if (checkService.checkToken(user_id, token, map)) {
				ApiU_dynamic_reply dynamic_reply = apiU_dynamic_replyService
						.findU_dynamic_replyById(Integer.valueOf(id));
				dynamic_reply.setIs_delete(1);
				apiU_dynamic_replyService.updateU_dynamic_reply(dynamic_reply);
				// return
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "删除成功！");
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		JsonUtil.printJson(response, JsonUtil.object2json(map));

	}

	/**
	 * State=1 不看他的动态， 2不让他看我的动态
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("seeDynamicsListState")
	public void seeDynamicsListState(HttpServletRequest request, HttpServletResponse response, String user_id,
			String token, String state, PageInfo page) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> params = new HashMap<String, Object>();
		try {
			if (checkService.checkToken(user_id, token, map)) {
				params.put("user_id", user_id);
				params.put("state", state);
				List<ApiU_dynamic_rule> rule_list = this.apiU_dynamic_ruleService.dynamic_rule(params, page);

				// return
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "操作成功！");
				map.put(Utils.DATAS, rule_list);
				map.put(Utils.Page, page);
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		JsonUtil.printJson(response, JsonUtil.object2json(map));

	}

	/**
	 * 不看他的动态
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("notSeeHisDynamics")
	public void notSeeHisDynamics(HttpServletRequest request, HttpServletResponse response, String user_id,
			String token, String to_uid) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> params = new HashMap<String, Object>();
		try {
			if (checkService.checkToken(user_id, token, map)) {
				params.put("user_id", user_id);
				params.put("to_uid", to_uid);
				int ret = this.apiU_dynamic_ruleService.notSeeHisDynamics(params);
				if (ret > 0) {
					map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
					map.put(Utils.MESSAGE, "操作成功！");
				} else {
					map.put(Utils.RESULT, Utils.RESULT_RC_PARAMTER_ERROR);
					map.put(Utils.MESSAGE, "操作失败！");
				}
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 不让他看我的动态
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("preventSeeMyDynamics")
	public void preventSeeMyDynamics(HttpServletRequest request, HttpServletResponse response, String user_id,
			String token, String to_uid) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> params = new HashMap<String, Object>();
		try {
			if (checkService.checkToken(user_id, token, map)) {
				params.put("user_id", to_uid);
				params.put("to_uid", user_id);
				int ret = this.apiU_dynamic_ruleService.notSeeHisDynamics(params);
				if (ret > 0) {
					map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
					map.put(Utils.MESSAGE, "操作成功！");
				} else {
					map.put(Utils.RESULT, Utils.RESULT_RC_PARAMTER_ERROR);
					map.put(Utils.MESSAGE, "操作失败！");
				}
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}
}
